/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.controller.admin  
 */
package com.apache.bid.controller.admin;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.attachment.entity.AttachmentStore;
import com.apache.bid.common.BidCommonUtil;
import com.apache.bid.common.BidHallUtil;
import com.apache.bid.common.Constant;
import com.apache.bid.common.TeaUtil;
import com.apache.bid.common.WbdToolsUtil;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.common.vo.BidItemCacheVo;
import com.apache.bid.common.vo.BidSessionCacheVo;
import com.apache.bid.common.vo.ItemPriceVo;
import com.apache.bid.entity.BidApply;
import com.apache.bid.entity.BidInfoBaojia;
import com.apache.bid.entity.BidItem;
import com.apache.bid.entity.BidItemHistory;
import com.apache.bid.entity.BidItemPrice;
import com.apache.bid.entity.BidItemVip;
import com.apache.bid.entity.BidLog;
import com.apache.bid.entity.BidMaxContent;
import com.apache.bid.entity.BidPub;
import com.apache.bid.entity.BidSession;
import com.apache.bid.manager.BidItemManager;
import com.apache.bid.manager.BidLogManager;
import com.apache.bid.manager.UnityBaseManager;
import com.apache.cache.util.Validator;
import com.apache.client.AttaCoreClient;
import com.apache.database.model.Page;
import com.apache.rpc.client.RpcProtoclClient;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.PBOSSOTools;
import com.apache.uct.common.ToolsUtil;

/**
 * description:  大厅
 * @author Hou Dayu 创建时间：2016-3-25  
 * 
 */
@Controller
@RequestMapping("admin/hall")
public class HallAction {
	protected Logger log = Logger.getLogger(getClass());

	@Autowired
	private BidItemManager bidItemManager;
	@Autowired
	private BidLogManager bidLogManager;

	//通用列表查询数据
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/rf" }, method = { RequestMethod.GET })
	@ResponseBody
	protected Object listData(HttpServletRequest request, String page, String rows) {
		Map<String, Object> params = new HashMap<String, Object>();
		String methodKey = request.getParameter("methodKey");
		if ("itemList".equals(request.getParameter("methodKey"))
				|| "itemHistoryList".equals(request.getParameter("methodKey"))) {
			if (ToolsUtil.isNotNull(request.getParameter("itemName"))) {
				params.put("itemName", request.getParameter("itemName"));
			}
			params.put("sessionId", request.getParameter("sessionId"));
			params.put("direction", request.getParameter("direction"));
			params.put("bidMode", request.getParameter("bidMode"));
			if ("itemList".equals(request.getParameter("methodKey"))) {
				params.put("itemStatus", Constant.getInstance().getItemConfig("statusPubslish"));
			}
			if ("itemHistoryList".equals(request.getParameter("methodKey"))) {
				params.put("bidMode", request.getParameter("bidMode"));
				params.put("itemName", request.getParameter("itemName"));
			}

		} else if ("sessionList".equalsIgnoreCase(methodKey)) {
			params.put("status", request.getParameter("status"));
			params.put("direction", request.getParameter("direction"));
		} else if ("applyOneOrList".equalsIgnoreCase(methodKey)) {
			params.put("userName", request.getParameter("userName"));
			params.put("sessionId", request.getParameter("sessionId"));
		} else if ("itemIdList".equalsIgnoreCase(methodKey)) {
			params.put("userName", request.getParameter("userName"));
		} else if ("contentList".equalsIgnoreCase(methodKey)) {
			params.put("contentType", request.getParameter("contentType"));
			params.put("objId", request.getParameter("objId"));
			params.put("objType", request.getParameter("objType"));
			params.put("title", request.getParameter("title"));
		}
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (ToolsUtil.isNotNull(request.getParameter("groupId"))) {
			params.put("groupId", ToolsUtil.isNull(request.getParameter("groupId"), ""));
		}
		if (Validator.isNotNull(rows)) {//rows为空表示不进行分页处理
			params.put("pageSize", Validator.getDefaultStr(rows, "10"));
			params.put("pageIndex", Validator.getDefaultStr(page, "1"));

			log.info("methodKey=" + methodKey + ";请求参数=" + params);
			ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", methodKey, params,
					BidCommonUtil.getInstance().getInterfaceRegister());
			if (!ToolsUtil.isEmpty(entity.getEntity())) {
				Page pageList = (Page) entity.getEntity();//分页
				mapData.put("total", pageList.getCount());//dataGrid所需参数
				if ("itemIdList".equalsIgnoreCase(methodKey)) {//根据itemIdList查缓存得到itemList
					BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
					List<BidItem> itemList = new ArrayList<BidItem>();
					BidItem bidItem = null;
					List listTemp = pageList.getPageObjects();
					if (listTemp != null) {
						for (int i = 0; i < listTemp.size(); i++) {
							boolean mark = cache.checkCacheObject(cache.item_prefix + listTemp.get(i).toString());
							if (mark) {
								BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix
										+ listTemp.get(i).toString());
								bidItem = (BidItem) itemVo;
								itemList.add(bidItem);
							}
						}
					}
					mapData.put("rows", itemList);//dataGrid所需数据对象集合
				} else {
					mapData.put("rows", pageList.getPageObjects());//dataGrid所需数据对象集合
				}
			}
		} else {
			log.info("methodKey=" + methodKey + ";请求参数=" + params);
			ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", methodKey, params,
					BidCommonUtil.getInstance().getInterfaceRegister());
			if (!ToolsUtil.isEmpty(entity.getEntity())) {
				List list = (List) entity.getEntity();
				mapData.put("total", list.size());//dataGrid所需参数
				if ("itemIdList".equalsIgnoreCase(methodKey)) {//根据itemIdList查缓存得到itemList
					BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
					List<BidItem> itemList = new ArrayList<BidItem>();
					BidItem bidItem = null;
					for (int i = 0; i < list.size(); i++) {
						boolean mark = cache.checkCacheObject(cache.item_prefix + list.get(i).toString());
						if (mark) {
							BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix
									+ list.get(i).toString());
							bidItem = (BidItem) itemVo;
							itemList.add(bidItem);
						}
					}
					mapData.put("rows", itemList);//dataGrid所需数据对象集合
				} else {
					mapData.put("rows", list);//dataGrid所需数据对象集合
				}
			}
		}
		return mapData;
	}

	/**
	 * 跳转到session下面的标的详情页面
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/session/{id}", method = { RequestMethod.GET })
	public ModelAndView gotoSesssion(HttpServletRequest request, @PathVariable String id) {
		ModelAndView view = new ModelAndView("hall/hall");
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("session");
		LoginUser loginUser = PBOSSOTools.getLoginUser(request);
		BidSession session = null;
		if (cache.checkCacheObject(BidCacheManager.session_prefix + id)) {
			session = (BidSession) cache.getCacheCloneByKey(BidCacheManager.session_prefix + id);

			String applyKey = BidCacheManager.apply_prefix;
			if (!Constant.SETYPE_HD.equals(session.getSessionType())) {
				applyKey += loginUser.getUserEname() + "_" + session.getSessionId();
				view.addObject("apply", cache.getCacheCloneByKey(applyKey));
			}
			view.addObject("pub", cache.getCacheObjectByKey(BidCacheManager.pub_prefix + session.getSessionId()));
		} else {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("sessionId", id);
			params.put("selectPub", "T");
			params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
			ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", "sessionEntity", params,
					BidCommonUtil.getInstance().getInterfaceRegister());
			BidSessionCacheVo scVo = null;
			if (!ToolsUtil.isEmpty(entity.getEntity())) {
				scVo = (BidSessionCacheVo) entity.getEntity();
				session = (BidSession) scVo;
				view.addObject("pub", scVo.getPub());
			}
		}
		if (null != session) {
			view.addObject("session", session);
			String thisTxt = "";
			if ("1".equals(session.getSessionType())) {
				thisTxt = "专厅";
			} else if ("2".equals(session.getSessionType())) {
				thisTxt = "专场";
			} else if ("3".equals(session.getSessionType())) {
				thisTxt = "专组";
			}
			String bidMode = session.getSessionMode();
			view.addObject("thisTxt", thisTxt);
			view.addObject("bidMode", bidMode);
			view.addObject("sessionType", session.getSessionType());

			String applyKey = BidCacheManager.apply_prefix;
			if (!Constant.SETYPE_HD.equals(session.getSessionType())) {
				applyKey += loginUser.getUserEname() + "_" + session.getSessionId();
				view.addObject("apply", cache.getCacheCloneByKey(applyKey));
			}
			view.addObject("pub", cache.getCacheObjectByKey(BidCacheManager.pub_prefix + session.getSessionId()));
			view.addObject("loginUser", loginUser);
			view.addObject("itemId", "0");
			view.addObject("sessionId", id);

			List itemGroupList = new ArrayList();
			//查询分组列表
			if ("T".equals(session.getIfGroup())) {
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
				params.put("sessionId", id);
				ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", "itemGroup", params,
						BidCommonUtil.getInstance().getInterfaceRegister());
				if (!ToolsUtil.isEmpty(entity.getEntity())) {
					itemGroupList = (List) entity.getEntity();
				}
			}
			view.addObject("itemGroupList", itemGroupList);

			//累计session浏览次数
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
			params.put("sessionId", id);
			RpcProtoclClient.getInstance().doService("wbdCacheService", "sessionBrowsing", params,
					BidCommonUtil.getInstance().getInterfaceRegister());
		} else {
			request.setAttribute("errors", "专组已结束");
			return new ModelAndView("hall/error");
		}
		return view;
	}

	@RequestMapping(value = { "/item/{id}" }, method = { RequestMethod.POST })
	@ResponseBody
	public Object viewItem(HttpServletRequest request, @PathVariable String id) {
		LoginUser loginUser = PBOSSOTools.getLoginUser(request);
		Map<String, Object> data = BidHallUtil.getInstance().getItemById(loginUser, id);
		return data;
	}

	/**
	 * 跳转到item标的详情页面
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/item/{id}" }, method = { RequestMethod.GET })
	public ModelAndView gotoitem(HttpServletRequest request, @PathVariable String id) {
		String defStr = "hall/hall";
		String thisTxt = "标的";
		String sessionId = "0";
		String sessionType = "3";
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		boolean mark = cache.checkCacheObject(BidCacheManager.item_prefix + id);
		if (!mark) {
			request.setAttribute("errors", "竞价已结束");
			return new ModelAndView("hall/error");
		}
		BidItemCacheVo cacheVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix + id);
		//		if (Constant.BIDMODE_YCXASC.equals(cacheVo.getBidMode())
		//				|| Constant.BIDMODE_YCXDESC.equals(cacheVo.getBidMode())) {
		//			defStr = "hall/oneBaojia";
		//		}
		ModelAndView view = new ModelAndView(defStr);
		view.addObject("itemId", id);
		if (mark) {
			BidItem itemCache = (BidItem) cacheVo;
			view.addObject("item", itemCache);
			BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix + id);
			view.addObject("price", price);
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			String vipKey = BidCacheManager.item_vip_prefix + loginUser.getUserEname() + "_" + id;
			BidItemVip vip = (BidItemVip) BidCacheFactory.getInstance().getCacheManager("itemVip")
					.getCacheObjectByKey(vipKey);
			String bidMode = itemCache.getBidMode();
			BidPub pub = BidCommonUtil.getInstance().getBidPub(cacheVo, cache);
			String applyKey = BidCacheManager.apply_prefix;
			if (!Constant.SETYPE_HD.equals(cacheVo.getSessionType())) {
				applyKey += loginUser.getUserEname() + "_" + cacheVo.getSessionId();
			} else {
				applyKey += loginUser.getUserEname() + "_" + cacheVo.getItemId();
			}

			List itemGroupList = new ArrayList();
			if (!"0".equals(cacheVo.getSessionId())) {
				BidSession session = (BidSession) cache.getCacheCloneByKey(cache.session_prefix
						+ cacheVo.getSessionId());
				view.addObject("session", session);
				sessionId = session.getSessionId();
				sessionType = session.getSessionType();
				if ("1".equals(session.getSessionType())) {
					thisTxt = "专厅";
				} else if ("2".equals(session.getSessionType())) {
					thisTxt = "专场";
				} else if ("3".equals(session.getSessionType())) {
					thisTxt = "专组";
				}
				//查询分组列表
				if ("T".equals(session.getIfGroup())) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
					params.put("sessionId", sessionId);
					ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", "itemGroup", params,
							BidCommonUtil.getInstance().getInterfaceRegister());
					if (!ToolsUtil.isEmpty(entity.getEntity())) {
						itemGroupList = (List) entity.getEntity();
					}
				}
			}
			BidApply apply = (BidApply) cache.getCacheCloneByKey(applyKey);
			view.addObject("apply", apply);
			view.addObject("itemGroupList", itemGroupList);
			view.addObject("loginUser", loginUser);
			view.addObject("pub", pub);
			view.addObject("thisTxt", thisTxt);
			view.addObject("bidMode", bidMode);
			view.addObject("sessionId", sessionId);
			view.addObject("sessionType", sessionType);
			if (ToolsUtil.isEmpty(vip)) {
				view.addObject("myLevel", "0");
			} else {
				view.addObject("myLevel", StrUtil.doNull(vip.getVipLevel(), "0"));
			}
			//累计session浏览次数
			if (!"0".equals(cacheVo.getSessionId())) {
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
				params.put("sessionId", cacheVo.getSessionId());
				RpcProtoclClient.getInstance().doService("wbdCacheService", "sessionBrowsing", params,
						BidCommonUtil.getInstance().getInterfaceRegister());
			}

			//			//获取此标的对应的图片附件列表
			//			List attaList = getItemPicAttaList(request, id);
			//			request.setAttribute("attaList", attaList);
			//			request.setAttribute("attaSize", attaList.size());
		}
		return view;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/content/{id}", method = { RequestMethod.GET })
	public ModelAndView gotoContent(HttpServletRequest request, @PathVariable String id) {
		String viewPage = "hall/content";
		BidMaxContent content = new BidMaxContent();
		ModelAndView view = new ModelAndView(viewPage);

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("infoId", id);
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", "contentEntity", params,
				BidCommonUtil.getInstance().getInterfaceRegister());
		BidSessionCacheVo scVo = null;
		if (!ToolsUtil.isEmpty(entity.getEntity())) {
			content = (BidMaxContent) entity.getEntity();
			if (content.getContentType().equals("采购公告")) {
				viewPage = "hall/caigou-content";
			}
			view = new ModelAndView(viewPage);
			view.addObject("content", content);
		}

		return view;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/toEnd" }, method = { RequestMethod.GET })
	public ModelAndView toEnd(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("hall/itemEnd");
		String itemId = request.getParameter("itemId");
		view.addObject("itemId", itemId);
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		boolean mark = cache.checkCacheObject(BidCacheManager.item_prefix + itemId);
		if (mark) {
			BidItemCacheVo cacheVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix + itemId);
			BidItem itemCache = (BidItem) cacheVo;
			view.addObject("item", itemCache);
			BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix + itemId);
			view.addObject("price", price);
		}
		return view;
	}

	//最高报价方加价
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/bidAdd" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg bidAdd(HttpServletRequest request, String myPrice, String itemId) {
		ResultMsg msg = new ResultMsg("T", "报价成功");
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix + itemId);
		try {
			if (ToolsUtil.isEmpty(price)) {
				msg = new ResultMsg("F", "您报价的标的不存在或已结束报价");
				return msg;
			}
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			if (ToolsUtil.isEmpty(loginUser)) {
				msg = new ResultMsg("F", "您还没有登录不能进行加价");
				return msg;
			}
			BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix + price.getItemId());
			String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmss();
			String status = BidCommonUtil.getInstance().getStatus(price, bidTime);
			if (!"D".equals(status)) {
				msg = new ResultMsg("F", "标的不在加价期,不能进行加价");
				return msg;
			}
			if (!loginUser.getUserEname().equals(price.getUserName())) {
				msg = new ResultMsg("F", "您不是最高报价人,不能进行加价");
				return msg;
			}

			//////写报价
			Map<String, Object> params = new HashMap<String, Object>();
			if (!Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
				params.put("syncObjId", itemVo.getSessionId());
			} else {
				params.put("syncObjId", itemVo.getItemId());
			}
			params.put("itemId", itemId);
			params.put("userEname", loginUser.getUserEname());
			//params.put("bidTime", bidTime);
			params.put("bidNum", StrUtil.doNull(request.getParameter("bidNum"), "1"));
			params.put("userIp", this.getUserIp(request));
			BidPub pub = BidCommonUtil.getInstance().getBidPub(itemVo, cache);
			//写入报价
			msg = BidHallUtil.getInstance().bidSend(params, msg, pub, myPrice, status, itemVo.getBidMode());
		} catch (Exception e) {
			msg = new ResultMsg("F", "系统异常，请重试");
		}
		return msg;
	}

	//行权
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/bidXingquan" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg bidXingquan(HttpServletRequest request, String itemId) {
		ResultMsg msg = new ResultMsg("T", "行权成功");
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix + itemId);
		try {
			if (ToolsUtil.isEmpty(price)) {
				msg = new ResultMsg("F", "您报价的标的不存在或已结束报价");
				return msg;
			}
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			if (ToolsUtil.isEmpty(loginUser)) {
				msg = new ResultMsg("F", "您还没有登录不能进行行权");
				return msg;
			}
			BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix + price.getItemId());
			String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmss();
			String status = BidCommonUtil.getInstance().getStatus(price, bidTime);
			if (!"E".equals(status)) {
				msg = new ResultMsg("F", "标的不在行权期,不能进行行权");
				return msg;
			}

			//////写报价
			Map<String, Object> params = new HashMap<String, Object>();
			if (!Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
				params.put("syncObjId", itemVo.getSessionId());
			} else {
				params.put("syncObjId", itemVo.getItemId());
			}
			params.put("itemId", itemId);
			params.put("userEname", loginUser.getUserEname());
			//params.put("bidTime", bidTime);
			params.put("bidNum", StrUtil.doNull(request.getParameter("bidNum"), "1"));
			params.put("userIp", this.getUserIp(request));
			BidPub pub = BidCommonUtil.getInstance().getBidPub(itemVo, cache);
			String myPrice = price.getLastValue();
			if (Constant.BIDMODE_YCXASC.equals(itemVo.getBidMode())
					|| Constant.BIDMODE_YCXDESC.equals(itemVo.getBidMode())) {
				if ("0".equals(myPrice) || ToolsUtil.isNull(myPrice)) {
					myPrice = itemVo.getFirstValuePre();
				} else {
					myPrice = TeaUtil.decryptByTea(myPrice);
				}
			}
			//写入报价
			msg = BidHallUtil.getInstance().bidSend(params, msg, pub, myPrice, status, itemVo.getBidMode());
		} catch (Exception e) {
			msg = new ResultMsg("F", "系统异常，请重试");
		}
		return msg;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/bidSend" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg bidSend(HttpServletRequest request, String myPrice, String itemId) {
		ResultMsg msg = new ResultMsg("T", "报价成功");
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix + itemId);
		try {
			if (ToolsUtil.isEmpty(price)) {
				msg = new ResultMsg("F", "您报价的标的不存在或已结束报价");
				return msg;
			}
			LoginUser loginUser = PBOSSOTools.getLoginUser(request);
			if (ToolsUtil.isEmpty(loginUser)) {
				msg = new ResultMsg("F", "您还没有登录不能进行报价");
				return msg;
			}
			BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheCloneByKey(cache.item_prefix + price.getItemId());
			String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
			String status = BidCommonUtil.getInstance().getStatus(price, bidTime);

			//////写报价开始
			Map<String, Object> params = new HashMap<String, Object>();
			//条件验证
			msg = BidCommonUtil.getInstance().getCheckItem(status, myPrice, loginUser.getUserEname(), itemVo, price);
			if (!ToolsUtil.isEmpty(msg)) {
				return msg;
			}
			if (!Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
				params.put("syncObjId", itemVo.getSessionId());
			} else {
				params.put("syncObjId", itemVo.getItemId());
			}
			params.put("itemId", itemId);
			params.put("userEname", loginUser.getUserEname());
			//params.put("bidTime", bidTime);
			params.put("bidNum", StrUtil.doNull(request.getParameter("bidNum"), "1"));
			params.put("userIp", this.getUserIp(request));
			BidPub pub = BidCommonUtil.getInstance().getBidPub(itemVo, cache);
			//写入报价
			msg = BidHallUtil.getInstance().bidSend(params, msg, pub, myPrice, status, itemVo.getBidMode());
		} catch (ParseException e) {
			msg = new ResultMsg("F", "系统异常，请重试");
		}
		return msg;
	}

	@RequestMapping(value = { "/bidGet" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object bidGet(HttpServletRequest request, HttpServletResponse response, String itemId) {
		LoginUser user = PBOSSOTools.getLoginUser(request);
		String bidNum = request.getParameter("bidNum");
		Map<String, Object> data = BidHallUtil.getInstance().bidGet(user, itemId, bidNum);
		return data;
	}

	/**
	 * description:  接标的ids获取动态信息
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = { "/cacheList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object stopItemsss(HttpServletRequest request, HttpServletResponse response, String ids) {
		String[] str = ids.split(",");
		List<String> keys = new ArrayList<String>();
		for (int i = 0; i < str.length; i++) {
			keys.add(str[i]);
		}
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		List list = cache.getObjects(keys, BidCacheManager.item_prefix);
		Map<String, Object> data = new HashMap<String, Object>();
		int count = list.size();
		if (!Validator.isEmpty(list)) {
			List result = new ArrayList();
			String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
			for (int i = 0; i < count; i++) {
				BidItemCacheVo itemVo = (BidItemCacheVo) list.get(i);
				ItemPriceVo pvo = new ItemPriceVo();
				BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(cache.item_price_prefix
						+ itemVo.getItemId());
				try {
					pvo.setBidTimes(price.getBidTimes());
					pvo.setItemId(price.getItemId());
					pvo.setLastValue("0".equals(price.getLastValue()) ? price.getFirstValue() : price.getLastValue());
					pvo.setLastBidTime(price.getLastBidTime());
					pvo.setUserName(price.getUserName());
					String status = BidCommonUtil.getInstance().getStatus(price, bidTime);
					long spareTime = BidHallUtil.getInstance()
							.getSpareTime(status, price, bidTime, itemVo.getBidMode());
					pvo.setSpareTime(spareTime);
					pvo.setStatus(status);
				} catch (Exception e) {
					continue;
				}
				result.add(pvo);
			}
			data.put("rows", result);
			data.put("total", result.size());
		}

		return data;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/baojiaList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object stopItemBaojia(HttpServletRequest request, HttpServletResponse response, String itemId) {
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		List list = (List) cache.getCacheCloneByKey(BidCacheManager.jingjia_prefix + itemId);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", list.size());
		data.put("rows", list);
		return data;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/jingjiaList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object jingjiaListData(HttpServletRequest request, HttpServletResponse response, String itemId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		Map<String, Object> data = new HashMap<String, Object>();
		String methodKey = request.getParameter("methodKey");
		log.info("methodKey=" + methodKey + ";请求参数=" + params);
		if (Validator.isNull(itemId)) {
			data.put("flag", "F");
			data.put("msg", "缺少必要的参数！");
		}
		params.put("itemId", itemId);
		ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", methodKey, params,
				BidCommonUtil.getInstance().getInterfaceRegister());
		if (ToolsUtil.isEmpty(entity) || "false".equals(entity.getResult())) {
			data.put("flag", "F");
			data.put("msg", "查询失败或通信失败！");
		} else {
			List list = (List) entity.getEntity();
			if (!ToolsUtil.isEmpty(list)) {
				data.put("total", list.size());
				data.put("rows", list);
			}
		}
		return data;
	}

	//判断申请购买人是否已经申请过
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/applyCheck" }, method = { RequestMethod.GET })
	@ResponseBody
	public ResultMsg applyCheck(HttpServletRequest request, HttpServletResponse response, BidApply apply) {
		ResultMsg msg = new ResultMsg("F", "通讯异常");
		Map<String, Object> params = new HashMap<String, Object>();
		Map map = WbdToolsUtil.getInstance().toMapDelNull(apply);
		log.info("竞买申请判断是否提交了申请，参数请求：" + map);
		params.putAll(map);
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", "applyList", params,
				BidCommonUtil.getInstance().getInterfaceRegister());
		msg = new ResultMsg("T", "可以申请");
		if ("true".equals(entity.getResult()) && entity.getEntity() != null) {
			List list = (List) entity.getEntity();
			log.info("执行查询结果记录数：" + list.size());
			if (list.size() > 0) {
				msg = new ResultMsg("F", "您已经发起过竞买申请,不能重复申请");
			}
		}
		return msg;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/apply" }, method = { RequestMethod.POST })
	@ResponseBody
	public ResultMsg apply(HttpServletRequest request, BidApply apply) {
		ResultMsg msg = new ResultMsg("T", "报价成功");

		Map<String, Object> params = new HashMap<String, Object>();
		String itemId = apply.getItemId();
		String sessionId = apply.getSessionId();

		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("apply");

		BidPub pub = null;
		if (ToolsUtil.isNotNull(sessionId) && !"0".equals(sessionId)) {
			pub = (BidPub) cache.getCacheObjectByKey(cache.pub_prefix + sessionId);
			apply.setItemId("0");
		} else {
			pub = (BidPub) cache.getCacheObjectByKey(cache.pub_prefix + itemId);
		}
		Map map = WbdToolsUtil.getInstance().toMapDelNull(apply);
		params.putAll(map);
		ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdCacheService", "saveApply", params,
				BidCommonUtil.getInstance().getInterfaceRegister(pub.getBjServer(), pub.getBjPort()));
		msg = new ResultMsg("true".equals(entity.getResult()) ? "T" : "F", entity.getMessage());
		return msg;
	}

	//从缓存中获取sesion的浏览次数
	@RequestMapping(value = { "/sessionBrowsing" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object sessionBrowsing(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("flag", "F");
		String sessionIdList = request.getParameter("sessionIdList");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		params.put("sessionIdList", sessionIdList);
		ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdCacheService", "sessionBrowsing", params,
				BidCommonUtil.getInstance().getInterfaceRegister());
		if ("true".equals(entity.getResult()) && entity.getEntity() != null) {
			data.put("flag", "T");
			data.put("rows", entity.getEntity());
		}
		return data;
	}

	//各标的历史报价和竞价列表
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/itemInfoList" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object itemInfoList(HttpServletRequest request, HttpServletResponse response, String itemId) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("total", "0");//dataGrid所需参数
		data.put("rows", "");//dataGrid所需数据对象集合
		String methodKey = "jingjiaList";//这块回头改活，还得查jingjiaList
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("itemId", itemId);//item_id
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		ResultEntity item = RpcProtoclClient.getInstance().doService("wbdService", "itemHistoryEntity", params,
				BidCommonUtil.getInstance().getInterfaceRegister());
		if ("true".equals(item.getResult()) && item.getEntity() != null) {
			BidItemHistory bidItem = (BidItemHistory) item.getEntity();
			if (Constant.BIDMODE_YCXASC.equals(bidItem.getBidMode())
					|| Constant.BIDMODE_YCXDESC.equals(bidItem.getBidMode())) {
				methodKey = "baojiaList";
			}
			ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", methodKey, params,
					BidCommonUtil.getInstance().getInterfaceRegister());
			if ("true".equals(entity.getResult()) && entity.getEntity() != null) {
				List list = (List) entity.getEntity();
				data.put("total", list.size());
				data.put("rows", list);
			}
		}
		return data;
	}

	/**
	 * description:  获取大字段内容
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/maxContent" }, method = { RequestMethod.POST })
	@ResponseBody
	public Object maxContent(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		String objId = request.getParameter("objId");
		String objType = request.getParameter("objType");
		String contentType = request.getParameter("contentType");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("objId", objId);
		params.put("objType", objType);
		params.put("contentType", contentType);
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", "contentList", params,
				BidCommonUtil.getInstance().getInterfaceRegister());
		if ("true".equals(entity.getResult()) && entity.getEntity() != null) {
			List list = (List) entity.getEntity();
			data.put("total", list.size());
			data.put("rows", list);
		}
		return data;
	}

	/**
	 * description:  添加阅读记录
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/readRecord" }, method = { RequestMethod.POST })
	@ResponseBody
	public Object readRecord(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		String sessionId = request.getParameter("sessionId");
		String userId = request.getParameter("userId");
		String logName = request.getParameter("logName");
		String logContent = request.getParameter("logContent");
		String createTime = DateUtils.getNow();
		String whoUserName = request.getParameter("userName");
		String orgCname = request.getParameter("orgCname");
		String objectType = request.getParameter("objectType");
		String objectId = request.getParameter("objectId");
		String objectName = request.getParameter("objectName");

		String ip = getUserIp(request);

		BidLog log = new BidLog();
		log.setUserId(userId);
		log.setWhoUserName(whoUserName);
		log.setLogName(logName);
		log.setLogContent(logContent);
		log.setCreateTime(createTime);
		log.setOrgCname(orgCname);
		log.setObjectType(objectType);
		log.setObjectId(objectId);
		log.setObjectName(objectName);
		log.setSessionId(sessionId);
		log.setIp(ip);

		ParamsVo<BidLog> vo = new ParamsVo<BidLog>();
		vo.setObj(log);

		String result = bidLogManager.saveInfo(vo);
		data.put("flag", "F");
		data.put("msg", "操作失败！");
		if (StrUtil.isNotNull(result)) {
			data.put("flag", "T");
			data.put("msg", "操作成功！");
		}
		return data;
	}

	@RequestMapping(value = { "/list/viewRs" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object baojiasForFe(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("flag", "F");
		Map<String, Object> params = new HashMap<String, Object>();
		String itemId = request.getParameter("itemId");
		params.put("itemId", request.getParameter("itemId"));
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheCloneByKey(BidCacheManager.item_prefix + itemId);
		List<BidInfoBaojia> list = null;
		String itemNum = "";
		String bidMode = "";
		params.put("sysPass", ToolsUtil.getInstance().getValueByKey("push_to_dwusoft_pass"));
		if (ToolsUtil.isEmpty(itemVo)) {
			params.put("itemId", itemId);
			ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdService", "itemHistoryEntity", params,
					BidCommonUtil.getInstance().getInterfaceRegister());
			if (!ToolsUtil.isEmpty(entity.getEntity())) {
				BidItemHistory itemh = (BidItemHistory) entity.getEntity();
				itemNum = itemh.getItemNum();
				bidMode = itemh.getBidMode();
				entity = RpcProtoclClient.getInstance().doService("wbdCacheService", "findBaojias", params,
						BidCommonUtil.getInstance().getInterfaceRegister("", ""));
				if ("true".equals(entity.getResult()) && !ToolsUtil.isEmpty(entity.getEntity())) {
					list = (List<BidInfoBaojia>) entity.getEntity();
				}
			}
		} else {
			BidPub pub = BidCommonUtil.getInstance().getBidPub(itemVo, cache);
			ResultEntity entity = RpcProtoclClient.getInstance().doService("wbdCacheService", "findBaojias", params,
					BidCommonUtil.getInstance().getInterfaceRegister(pub.getBjServer(), pub.getBjPort()));
			if ("true".equals(entity.getResult()) && !ToolsUtil.isEmpty(entity.getEntity())) {
				list = (List<BidInfoBaojia>) entity.getEntity();
			}
			itemNum = itemVo.getItemNum();
			bidMode = itemVo.getBidMode();
		}
		if (!ToolsUtil.isEmpty(list)) {
			data.put("flag", "T");
			data.put("rows", BidHallUtil.getInstance().getFeBaojiaResult(itemNum, bidMode, list));
		}
		return data;
	}

	protected UnityBaseManager<BidItem> getBaseManager() {
		return bidItemManager;
	}

	/**
	 * description:  获取访问IP
	 * @param request 当前请求
	 * @return   
	 * @author Hou Dayu  
	 */
	protected String getUserIp(HttpServletRequest request) {
		String ip = "";
		try {
			ip = request.getHeader("x-forwarded-for");
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (Validator.isNull(ip) || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (Validator.isNotNull(ip) && ip.length() > 32) {
				ip = ip.substring(0, 32);
			}
		} catch (Exception e) {
		}
		return ip;
	}

	/**
	 * 获取单标的所关联的附件图片列表
	 * @param request
	 * @param objId 标的Id
	 */
	@SuppressWarnings("unchecked")
	private List getItemPicAttaList(HttpServletRequest request, String objId) {
		ResultEntity entAtta = AttaCoreClient.getAttachmentList(objId, "bidUpPicOne");
		List<AttachmentStore> attaList = new ArrayList<AttachmentStore>();
		if ("true".equals(entAtta.getResult()) && entAtta.getEntity() != null) {
			attaList = (List<AttachmentStore>) entAtta.getEntity();
		}
		return attaList;

	}

	/**
	 * 获取标的对应的多张图片列表
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = { "/itemPic" }, method = { RequestMethod.GET })
	@ResponseBody
	public Object itemPic(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		String objId = request.getParameter("objId");
		if (Validator.isNotNull(objId)) {
			List attaList = getItemPicAttaList(request, objId);
			data.put("attaSize", attaList.size());
			data.put("attaList", attaList);
		}
		return data;
	}
}
